#include "shogiplayer.h"

ShogiPlayer::ShogiPlayer(Player p) : m_player(p), m_pSocket(NULL) 
{
	m_state.setPlayerId(p);
}


bool ShogiPlayer::assignSocket(QTcpSocket* pSocket)
{
	bool bResult = false;
	
	if (pSocket != NULL)
	{	
		if (m_pSocket == NULL)
		{
			m_pSocket = pSocket;			
			connect(m_pSocket,SIGNAL(readyRead()),this,SLOT(readIncomingData()));
			
			LOGSERVER("Socket assigned.");
			m_state.changeState(HANDSHAKE);
		}		
	}

	return bResult;
}


void ShogiPlayer::readIncomingData()
{
	bool bCompleteData = false;
	QByteArray temporaryBuffer;
	QDataStream inStream(m_pSocket);			
	LOGSERVER("ri2");
	inStream.setVersion(QDataStream::Qt_4_0);
	LOGSERVER(QString("Buffer contains: ") + m_incomingData.constData());
	while (!inStream.atEnd() && !bCompleteData)
	{
		inStream >> temporaryBuffer;
		m_incomingData += temporaryBuffer;

		if (m_incomingData.contains(';'))
		{
			bCompleteData = true;
		}
	}
		
	if (bCompleteData)
	{
		// handle command
		LOGSERVER("Complete command read!");
		LOGSERVER((const char*)m_incomingData);
		receivedCommand();
		m_incomingData.clear();
	}
	else
	{
		// TODO: full command not read yet
		LOGSERVER("Complete command not read yet.");
	}		
		
}


void ShogiPlayer::receivedCommand()
{
	ShogiCommand cmd(m_player);

	if (cmd.parseCommand(&m_incomingData))
	{
		LOGSERVER("Command parsed successfully.");
		m_state.processCommand(cmd);
	}
	else
	{
		// TODO: Error could not parse command
		LOGSERVER("Could not parse command.");
	}
}






void ShogiPlayer::forceStateChange(GameState s)
{
	m_state.changeState(s);
}

